<template>
  <div class="admin-page" v-loading="pageLoading">
    <!-- 顶部标题栏 -->
    <header class="header">
      <div class="logo">
        <el-button type="primary" @click="handleBack" style="font-size: 16px;font-weight: bold;">              
          <el-icon style="font-size: 20px;">
                <Back />
              </el-icon>&nbsp;&nbsp;返回</el-button>
      </div>
      <h1>管理员列表</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <!-- 搜索框 -->
        <el-input v-model="searchText" placeholder="支持搜索账号、控制人" class="search-input">
          <template #append>
            <el-button type="primary" class="search-btn" @click="handleSearch">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>

        <!-- 筛选条件 -->
        <div class="filter-row">
          <el-select v-model="sortType" placeholder="排序：按权限数量(正序)">
            <el-option label="按权限数量(正序)" value="asc" />
            <el-option label="按权限数量(倒序)" value="desc" />
          </el-select>

          <el-select v-model="permissionType" placeholder="权限筛选：全部">
            <el-option label="权限筛选：全部" value="all" />
            <el-option label="用户管理" value="user_management" />
            <el-option label="会议管理" value="meeting_management" />
            <el-option label="活动管理" value="event_management" />
            <el-option label="签到管理" value="check_in_management" />
            <el-option label="新闻发布" value="news_release" />
            <el-option label="主办编辑" value="host_editor" />
            <el-option label="提案管理" value="proposal_management" />
            <el-option label="社情民意管理" value="social_opinion_management" />
            <el-option label="提案专项处理" value="proposal_special_handling" />
            <el-option label="社情民意专项处理" value="social_opinion_special_handling" />
          </el-select>

          <el-select v-model="statusType" placeholder="状态筛选：全部">
            <el-option label="状态筛选：全部" value="all" />
            <el-option label="已注销" value="已注销" />
            <el-option label="未注销" value="未注销" />
          </el-select>

          <div class="button-group" style="margin-left: auto;">
            <!-- 操作按钮 -->
            <el-button type="primary" @click="handleAddAdmin">新增管理员</el-button>
            <el-button type="primary" @click="handleExport" :loading="exportLoading">
              {{ exportLoading ? '导出中...' : '导 出' }}
            </el-button>
          </div>

        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <div class="admin-list">
          <!-- 添加表头 -->
          <div class="admin-header">
            <div class="header-item">账号</div>
            <div class="header-item">控制人</div>
            <div class="header-item">权限数量</div>
            <div class="header-item"></div>
          </div>

          <!-- 数据列表 -->
          <div v-if="tableData.length === 0" class="no-data">查无此数据</div>
          <div v-for="(item, index) in tableData" :key="index" class="admin-item">
            <div class="blue-line"></div>
            <div class="admin-info">
              <div class="info-value">{{ item.account }}</div>
              <div class="info-value">{{ item.controller }}</div>
              <div class="info-value">{{ item.permissions }}</div>
            </div>
            <div class="admin-actions">
              <el-button type="danger"  @click="handleDelete(item)" :disabled="item.status === '已注销'"
                :class="{ 'is-disabled': item.status === '已注销' }">
                {{ item.status === '已注销' ? '已注销' : '注销' }}
              </el-button>
              <el-button type="primary"  @click="handleDetail(item)">
                详情
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Back, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getAdmins, disableAdmin, exportAdmins } from '@/api/super'
import Time from '@/components/time.vue'
// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索和筛选状态
const searchText = ref('')
const sortType = ref('asc')
const permissionType = ref('all')
const statusType = ref('all')
const router = useRouter()

// 表格数据
const tableData = ref([])

const pageLoading = ref(false)
const tableLoading = ref(false)
const exportLoading = ref(false)

// 返回处理
const handleBack = () => {
  router.back()
}

// 获取管理员列表数据
const fetchAdminList = async () => {
  tableLoading.value = true
  try {
    const res = await getAdmins(
      pageNum.value,
      pageSize.value,
      sortType.value,
      permissionType.value,
      statusType.value,
      searchText.value
    )
    if (res.code === 200) {
      // 修改这里以匹配后端返回的数据结构
      tableData.value = res.data.items.map(item => ({
        aid: item.aid,
        account: item.account,
        controller: item.controller,
        // 计算权限总数
        permissions: [
          item.manageUsers,
          item.manageMeetings,
          item.manageEvents,
          item.manageCheckIns,
          item.publishNews,
          item.editHomePage,
          item.managePropositions,
          item.managePublic
        ].filter(Boolean).length,
        status: item.status
      }))
      total.value = res.data.total
    }
  } catch (error) {
    ElMessage.error('获取管理员列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  if (!searchText.value) {
    ElMessage.warning('请输入您要搜索的控制人');
    return;
  }
  pageNum.value = 1;
  fetchAdminList();
}

// 监听筛选条件变化
watch([sortType, permissionType, statusType], () => {
  pageNum.value = 1
  fetchAdminList()
})

// 分页处理
const onSizeChange = (val) => {
  pageSize.value = val
  fetchAdminList()
}

const onCurrentChange = (val) => {
  pageNum.value = val
  fetchAdminList()
}

// 新增管理员
const handleAddAdmin = () => {
  router.push('/admin/add')
}

const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    const response = await exportAdmins(
      sortType.value,
      permissionType.value,
      statusType.value,
      searchText.value
    );

    // 调试信息
    console.log('Response headers:', response.headers);
    console.log('Response type:', response.type);
    console.log('Response size:', response.size);

    // 检查响应是否为空
    if (!response || response.size === 0) {
      throw new Error('导出的文件为空');
    }

    // 检查响应类型
    const contentType = response.type;
    if (!contentType.includes('spreadsheetml.sheet')) {
      // 如果响应不是Excel文件，尝试读取错误信息
      const text = await response.text();
      throw new Error(text || '导出的文件格式不正确');
    }

    // 创建下载链接
    const blob = new Blob([response], { type: contentType });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `管理员列表_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('Export error:', error);
    ElMessage.error(error.message || '导出失败');
  } finally {
    exportLoading.value = false;
  }
}

// 注销管理员
const handleDelete = async (row) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm(`确定要注销 ${row.controller} 的账号吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用注销接口
    console.log('点击了', row.aid)
    const res = await disableAdmin(row.aid)
    if (res.code === 200) {
      // 显示注销成功提示
      ElMessage.success('注销成功')
      // 更新当前行状态
      row.status = '已注销'
      // 重新获取列表数据
      fetchAdminList()
    } else {
      // 显示注销失败提示
      ElMessage.error('注销失败')
    }
  } catch (error) {
    // 处理异常情况
    // 用户取消操作或接口调用失败
    if (error !== 'cancel') {
      ElMessage.error('注销失败')
    }
  }
}

// 查看详情
const handleDetail = (row) => {
  router.push({ path: `/admin/info/${row.aid}` })
}



onMounted(async () => {
  pageLoading.value = true
  try {
    await fetchAdminList()
  } finally {
    pageLoading.value = false
  }
})
</script>

<style scoped>
@import '@/assets/css/header/index.css';
@import '@/assets/css/list.css';

</style>
